import {defineStore} from 'pinia'
import {ref} from 'vue'
import {getCurrentUser, login as loginApi, logout as logoutApi} from '@/api/user'
import {getCartList} from '@/api/cart'

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', () => {
    // 状态定义
    const token = ref(localStorage.getItem('user_token') || '')
    const userInfo = ref(null)
    const isLoading = ref(false)

    /**
     * 登录
     * @param {Object} loginForm - 登录表单数据
     * @param {string} loginForm.username - 用户名
     * @param {string} loginForm.password - 密码
     */
    const login = async (loginForm) => {
        try {
            isLoading.value = true

            // 调用登录API
            const response = await loginApi(loginForm)
            const {token: authToken, user} = response.data

            // 保存token和用户信息
            token.value = authToken
            userInfo.value = user

            // 持久化存储token
            localStorage.setItem('user_token', authToken)

            return {success: true, data: response.data}
        } catch (error) {
            console.error('登录失败:', error)
            return {
                success: false,
                message: error.response?.data?.message || '登录失败，请重试'
            }
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 登出
     */
    const logout = async () => {
        try {
            // 调用登出API
            await logoutApi()
        } catch (error) {
            console.error('登出API调用失败:', error)
        } finally {
            // 清除状态
            token.value = ''
            userInfo.value = null

            // 清除本地存储
            localStorage.removeItem('user_token')
        }
    }

    /**
     * 获取当前用户信息
     */
    const fetchUserInfo = async () => {
        try {
            if (!token.value) {
                return {success: false, message: '未登录'}
            }

            const response = await getCurrentUser()
            userInfo.value = response.data

            return {success: true, data: response.data}
        } catch (error) {
            console.error('获取用户信息失败:', error)

            // 如果token无效，清除登录状态
            if (error.response?.status === 401) {
                logout()
            }

            return {
                success: false,
                message: error.response?.data?.message || '获取用户信息失败'
            }
        }
    }

    /**
     * 检查是否已登录
     */
    const isLoggedIn = () => {
        return !!token.value
    }

    /**
     * 获取用户显示名称
     */
    const getDisplayName = () => {
        if (!userInfo.value) return '未知用户'
        return userInfo.value.nickname || userInfo.value.username || '未知用户'
    }

    // 返回状态和方法
    return {
        // 状态
        token,
        userInfo,
        isLoading,

        // 方法
        login,
        logout,
        fetchUserInfo,
        isLoggedIn,
        getDisplayName
    }
})

/**
 * 购物车状态管理
 */
export const useCartStore = defineStore('cart', () => {
    // 状态定义
    const cartCount = ref(0)
    const cartSummary = ref(null)

    /**
     * 获取购物车统计信息
     */
    const fetchCartSummary = async () => {
        try {
            const response = await getCartList()
            const cartItems = response.data || []

            // 计算购物车统计
            const totalItems = cartItems.reduce((total, item) => total + item.quantity, 0)
            const totalAmount = cartItems.reduce((total, item) => total + parseFloat(item.subtotal || 0), 0)

            cartSummary.value = {
                totalItems,
                totalAmount: totalAmount.toFixed(2),
                itemCount: cartItems.length
            }
            cartCount.value = totalItems

            return {success: true, data: cartSummary.value}
        } catch (error) {
            console.error('获取购物车统计失败:', error)
            return {
                success: false,
                message: error.response?.data?.message || '获取购物车统计失败'
            }
        }
    }

    /**
     * 更新购物车数量
     */
    const updateCartCount = (count) => {
        cartCount.value = count
    }

    /**
     * 清空购物车状态
     */
    const clearCartState = () => {
        cartCount.value = 0
        cartSummary.value = null
    }

    // 返回状态和方法
    return {
        // 状态
        cartCount,
        cartSummary,

        // 方法
        fetchCartSummary,
        updateCartCount,
        clearCartState
    }
})